'use client'

import { useState, useEffect } from 'react'
import { useParams, useRouter } from 'next/navigation'
import { VmsCourse, VmsCourseSection } from '@/types/Model'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Calendar, BookOpen, Users, Eye, User, ExternalLink } from 'lucide-react'
import moment from 'moment'
import Link from 'next/link'

export default function PublicCoursePage() {
  const params = useParams()
  const router = useRouter()
  const token = params.token as string
  
  const [course, setCourse] = useState<VmsCourse | null>(null)
  const [sections, setSections] = useState<VmsCourseSection[]>([])
  const [otherCourses, setOtherCourses] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  
  useEffect(() => {
    fetchCourse()
  }, [token])



  const fetchCourse = async () => {
    try {
      const response = await fetch(`/api/course/public/${token}`)
      
      if (!response.ok) {
        if (response.status === 404) {
          setError('课程不存在或已下线')
        } else {
          setError('加载课程失败')
        }
        return
      }
      
      const data = await response.json()
      setCourse(data.course)
      setSections(data.sections || [])
      setOtherCourses(data.otherCourses || [])
    } catch (error) {
      console.error('Error fetching course:', error)
      setError('网络错误，请稍后重试')
    } finally {
      setLoading(false)
    }
  }



  // 辅助函数：安全地渲染HTML内容或纯文本
  const renderContent = (content: string) => {
    const hasHtmlTags = /<[^>]*>/g.test(content)
    
    if (hasHtmlTags) {
      return (
        <div 
          className="prose max-w-none text-gray-700 leading-relaxed"
          dangerouslySetInnerHTML={{ __html: content }}
        />
      )
    } else {
      return (
        <p className="text-gray-700 leading-relaxed whitespace-pre-wrap">
          {content}
        </p>
      )
    }
  }

  // 在组件内添加直接参与课程的处理函数
  const handleDirectJoin = () => {
    // 直接跳转到学习页面，完全跳过API调用
    router.push(`/course/${token}/learn`);
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p className="text-gray-600">加载中...</p>
        </div>
      </div>
    )
  }

  if (error || !course) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <div className="text-6xl mb-4">😕</div>
          <h1 className="text-2xl font-bold text-gray-800 mb-2">{error || '课程不存在'}</h1>
          <p className="text-gray-600">请检查链接是否正确</p>
        </div>
      </div>
    )
  }

  const publishedSections = sections.filter(section => section.published)

  return (
    <div className="min-h-screen bg-gray-50 flex flex-col">  
      {/* 发布者 Header */}
      {/* {course.user && ( */}
        <div className="bg-white border-b border-gray-200 shadow-sm">
          <div className="max-w-6xl mx-auto px-4 py-4 flex items-center justify-between">
            <div className="flex items-center space-x-4">
              <div className="w-12 h-12 bg-blue-100 rounded-full flex items-center justify-center overflow-hidden">
                  <User className="w-6 h-6 text-blue-500" />
              </div>
              <div>
                <h3 className="font-bold text-gray-900">{course.user?.name }</h3>
                <p className="text-sm text-gray-500">{course.user?.email}</p>
              </div>
            </div>
            <div>
              <Link href={`/user/${course.user?.id}/courses`}>
                <Button 
                  variant="outline" 
                  size="sm" 
                  className="text-blue-600 border-blue-200 hover:bg-blue-50"
                >
                  查看更多课程
                </Button>
              </Link>
            </div>
          </div>
        </div>
      {/* )} */}

      {/* 两栏布局：左侧课程信息，右侧参与和章节 */}
      <div className="max-w-6xl mx-auto px-4 py-8 md:py-12 lg:py-16 w-full flex-grow">  
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          {/* 左侧：课程信息 */}
          <div className="lg:col-span-2">
            {/* 课程标题和基本信息 */}
            <div className="bg-white rounded-xl shadow-sm overflow-hidden mb-8">
              {course.cover_image && (
                <div className="relative h-48 md:h-64 w-full overflow-hidden">
                  <img 
                    src={course.cover_image} 
                    alt={course.title}
                    className="w-full h-full object-cover"
                  />
                  {course.is_free && (
                    <div className="absolute top-4 right-4">
                      <Badge className="bg-green-500 hover:bg-green-600 text-white px-3 py-1 text-sm font-medium">
                        免费课程
                      </Badge>
                    </div>
                  )}
                </div>
              )}
              
              <div className="p-6">
                <h1 className="text-3xl font-bold mb-4">{course.title}</h1>
                {course.description && (
                  <p className="text-gray-600 mb-6">{course.description}</p>
                )}
                
                <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
                  <div className="bg-gray-50 rounded-lg p-3 text-center">
                    <Eye className="w-5 h-5 mx-auto mb-1 text-blue-500" />
                    <span className="block text-sm text-gray-500">观看次数</span>
                    <span className="font-semibold">{course.view_count}</span>
                  </div>
                  <div className="bg-gray-50 rounded-lg p-3 text-center">
                    <Users className="w-5 h-5 mx-auto mb-1 text-blue-500" />
                    <span className="block text-sm text-gray-500">学习人数</span>
                    <span className="font-semibold">{course.participant_count}</span>
                  </div>
                  <div className="bg-gray-50 rounded-lg p-3 text-center">
                    <BookOpen className="w-5 h-5 mx-auto mb-1 text-blue-500" />
                    <span className="block text-sm text-gray-500">章节数量</span>
                    <span className="font-semibold">{publishedSections.length}</span>
                  </div>
                  <div className="bg-gray-50 rounded-lg p-3 text-center">
                    <Calendar className="w-5 h-5 mx-auto mb-1 text-blue-500" />
                    <span className="block text-sm text-gray-500">发布日期</span>
                    <span className="font-semibold">{moment(course.created_at).format('YYYY/MM/DD')}</span>
                  </div>
                </div>
              </div>
            </div>
            
            {/* 课程介绍 */}
            {course.content_description && (
              <div className="bg-white rounded-xl shadow-sm overflow-hidden mb-8">
                <div className="p-6">
                  <h2 className="text-xl font-bold mb-4 flex items-center">
                    <span className="w-1 h-6 bg-blue-500 rounded-full mr-3"></span>
                    课程介绍
                  </h2>
                  {renderContent(course.content_description)}
                </div>
              </div>
            )}

            {/* 发布者的其他课程 */}
            {otherCourses.length > 0 && (
              <div className="bg-white rounded-xl shadow-sm overflow-hidden mb-8">
                <div className="p-6">
                  <h2 className="text-xl font-bold mb-4 flex items-center">
                    <span className="w-1 h-6 bg-blue-500 rounded-full mr-3"></span>
                    发布者的其他课程
                  </h2>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    {otherCourses.map((otherCourse) => (
                      <Link 
                        href={`/course/${otherCourse.access_token}`} 
                        key={otherCourse.id}
                        className="group block bg-gray-50 rounded-lg overflow-hidden hover:shadow-md transition-shadow duration-200"
                      >
                        <div className="flex h-full">
                          {otherCourse.cover_image ? (
                            <div className="w-24 h-24 flex-shrink-0">
                              <img 
                                src={otherCourse.cover_image} 
                                alt={otherCourse.title}
                                className="w-full h-full object-cover"
                              />
                            </div>
                          ) : (
                            <div className="w-24 h-24 bg-gray-200 flex-shrink-0 flex items-center justify-center">
                              <BookOpen className="w-8 h-8 text-gray-400" />
                            </div>
                          )}
                          <div className="p-3 flex-1">
                            <h3 className="font-medium text-gray-900 group-hover:text-blue-600 transition-colors line-clamp-2">
                              {otherCourse.title}
                            </h3>
                            <div className="flex items-center mt-2 text-xs text-gray-500">
                              <Eye className="w-3 h-3 mr-1" />
                              <span className="mr-3">{otherCourse.view_count}</span>
                              <Users className="w-3 h-3 mr-1" />
                              <span>{otherCourse.participant_count}</span>
                              {otherCourse.is_free && (
                                <Badge variant="outline" className="ml-2 bg-green-50 text-green-700 border-green-200 text-xs px-1.5 py-0">
                                  免费
                                </Badge>
                              )}
                            </div>
                          </div>
                        </div>
                      </Link>
                    ))}
                  </div>
                </div>
              </div>
            )}
          </div>
          
          {/* 右侧：参与课程和章节列表 */}
          <div className="lg:col-span-1">
            {/* 参与课程卡片 */}
            <div className="bg-white rounded-xl shadow-sm overflow-hidden mb-8 sticky top-4">
              <div className="p-6">
                <h2 className="text-xl font-bold mb-4">参与此课程</h2>
                <div className="space-y-4 mb-6">
                  <div className="flex items-center">
                    <div className="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center mr-3">
                      <BookOpen className="w-5 h-5 text-blue-500" />
                    </div>
                    <div>
                      <span className="block text-sm text-gray-500">总章节</span>
                      <span className="font-medium">{publishedSections.length} 个章节</span>
                    </div>
                  </div>
                  {course.is_free ? (
                    <div className="flex items-center">
                      <div className="w-10 h-10 rounded-full bg-green-100 flex items-center justify-center mr-3">
                        <span className="text-green-500 font-bold">免</span>
                      </div>
                      <div>
                        <span className="block text-sm text-gray-500">课程价格</span>
                        <span className="font-medium text-green-500">免费</span>
                      </div>
                    </div>
                  ) : null}
                </div>
                
                <Button 
                  size="lg" 
                  className="w-full bg-blue-600 hover:bg-blue-700" 
                  onClick={handleDirectJoin}
                >
                  立即参与课程
                </Button>
              </div>
            </div>
            
            {/* 章节列表 */}
            <div className="bg-white rounded-xl shadow-sm overflow-hidden">
              <div className="p-6">
                <h2 className="text-xl font-bold mb-4 flex items-center">
                  <span className="w-1 h-6 bg-blue-500 rounded-full mr-3"></span>
                  课程内容
                </h2>
                
                {publishedSections.length === 0 ? (
                  <div className="text-center py-8">
                    <BookOpen className="w-12 h-12 text-gray-300 mx-auto mb-3" />
                    <p className="text-gray-500">暂无已发布的课程内容</p>
                  </div>
                ) : (
                  <div className="space-y-3">
                    {publishedSections.map((section, index) => (
                      <div 
                        key={section.id}
                        className="border rounded-lg hover:border-blue-300 transition-colors"
                      >
                        <div className="p-4">
                          <div className="flex items-start">
                            <div className="w-8 h-8 bg-blue-100 text-blue-600 rounded-full flex items-center justify-center text-sm font-semibold mr-3 flex-shrink-0">
                              {index + 1}
                            </div>
                            <div className="flex-1 min-w-0">
                              <h3 className="text-base font-medium mb-1 truncate">{section.title}</h3>
                              <div className="flex items-center">
                                {section.is_free && (
                                  <Badge variant="outline" className="bg-green-50 text-green-700 border-green-200 mr-2">
                                    免费
                                  </Badge>
                                )}
                                <Button 
                                  variant="ghost" 
                                  size="sm"
                                  className="text-blue-600 hover:text-blue-700 hover:bg-blue-50 p-0 h-auto"
                                  onClick={() => router.push(`/course/${token}/learn?section=${section.id}`)}
                                >
                                  开始学习 →
                                </Button>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Footer */}
      <footer className="bg-white text-gray-400 body-font py-8">
        <div className="max-w-4xl mx-auto px-4 text-center">
          <p className="text-gray-400">© 2024 VideoFlow. 保留所有权利。</p>
        </div>
      </footer>

  
    </div>
  )
}
